﻿using KWT.DRG_DIP.API.Infrastructure;
using KWT.DRG_DIP.Common;
using KWT.DRG_DIP.DB;
using KWT.DRG_DIP.DO.System;
using KWT.DRG_DIP.DTO.Basic.User;
using KWT.DRG_DIP.DTO.User;
using KWT.DRG_DIP.PO.Basic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace KWT.DRG_DIP.API.Controllers.Basic
{
    /// <summary>
    /// 用户管理 
    /// </summary>
    [ApiExplorerSettings(GroupName = "basic")]
    public class UserController : BasicControllerBase
    {
        public EFContext ef { get; set; }
        public MainEFContext main { get; set; }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public OutputResult PageList(InPageList dto)
        {
            var q1 = ef.Set<Sys_User>().AsQueryable();
            var q2 = ef.Set<User_AreaRoleDeptCategory>().AsQueryable();
            var q3 = ef.Set<Tenant_Area>().AsQueryable();
            var q4 = ef.Set<Sys_Role>().AsQueryable();
            var q5 = ef.Set<Sys_Dept>().AsQueryable();
            var q6 = ef.Set<Sys_Category>().AsQueryable();

            if (!string.IsNullOrEmpty(dto.Phone))
            {
                q1 = q1.Where(x => x.Phone == dto.Phone);
            }
            if (!string.IsNullOrEmpty(dto.LoginName))
            {
                q1 = q1.Where(x => EF.Functions.Like(x.LoginName, $"%{dto.LoginName}%"));
            }
            if (!string.IsNullOrEmpty(dto.RealName))
            {
                q1 = q1.Where(x => EF.Functions.Like(x.RealName, $"%{dto.RealName}%"));
            }
            if (dto.Status > 0)
            {
                q1 = q1.Where(x => x.Status == dto.Status);
            }
            if (!string.IsNullOrEmpty(dto.AreaID))
            {
                q2 = q2.Where(x => x.AreaID == dto.AreaID);
            }
            if (!string.IsNullOrEmpty(dto.RoleID))
            {
                q2 = q2.Where(x => x.RoleID == dto.RoleID);
            }
            if (!string.IsNullOrEmpty(dto.DeptID))
            {
                q2 = q2.Where(x => x.DeptID == dto.DeptID);
            }
            if (!string.IsNullOrEmpty(dto.CategoryID))
            {
                q2 = q2.Where(x => x.CategoryID == dto.CategoryID);
            }

            var _q = (from a in q1
                      join b in q2 on a.UserID equals b.UserID
                      join c in q3 on b.AreaID equals c.AreaID
                      join d in q4 on b.RoleID equals d.RoleID
                      join e in q5 on b.DeptID equals e.DeptID
                      join f in q6 on b.CategoryID equals f.CategoryID
                      orderby a.AddTime descending
                      select new { a.UserID,a.Status,a.LoginName, a.RealName, a.Phone, a.AddTime, AreaName = c.Name, RoleName = d.Name, DeptName = e.Name, CategoryName = f.Name }
            );
            int total = _q.Count();
            var list = _q.ToPageList(dto.PageNo, dto.PageSize);
            return Output(list.Count > 0, "", "", new PageList<object>() { List = list, Total = total });
        }

        /// <summary>
        /// 禁用/启用
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public OutputResult Enabled(InEnabled dto)
        {
            if (CurrentUser.RoleID != "99")
            {
                return Fail("抱歉！您没有权限");
            }
            var user = ef.Find<Sys_User>(dto.UserID);
            user.Status = dto.Status;
            ef.Attach(user);
            var flag = ef.SaveChanges() > 0;
            return Output(flag, "操作成功！", "操作失败！");
        }

        /// <summary>
        /// 添加或修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(Output<string>), 200)]
        public OutputResult AddOrUpdate(InAddOrUpdate dto)
        {
            string tanentID = HttpContext.Request.Headers["TenantID"];
            if (string.IsNullOrWhiteSpace(dto.UserID))
            {
                var user = new Sys_User()
                {
                    UserID = "US" + snow_id.CreateId().ToString(),
                    Age = dto.Age,
                    Avatar = dto.Avatar,
                    Phone = dto.Phone,
                    NickName = dto.NickName,
                    RealName = dto.RealName,
                    Pwd = "MREHjLqRvaCNDaGr+ioltbWHLoxRA7jjfV08VKgk/cE=",
                    TenantID = tanentID,
                    Salt = "unwMVQi1",
                    LoginName = dto.LoginName,
                };
                main.Add(user);
                ef.Add(user);
                var list = new List<User_AreaRoleDeptCategory>();
                foreach (var item in dto.DeptRoleCategory)
                {
                    int i = dto.DeptRoleCategory.IndexOf(item);
                    if (item.Length == 3)
                    {
                        list.Add(new User_AreaRoleDeptCategory() { DeptID = item[0], AreaID = dto.AreaID[i], UserID = user.UserID, UAID = "UA" + snow_id.CreateId().ToString(), RoleID = item[1], CategoryID = item[2] });
                    }
                    else
                    {
                        list.Add(new User_AreaRoleDeptCategory() { DeptID = item[0], AreaID = dto.AreaID[i], UserID = user.UserID, UAID = "UA" + snow_id.CreateId().ToString(), RoleID = item[1], CategoryID = "" });
                    }

                }
                main.AddRange(list);
                ef.AddRange(list);
            }
            else
            {
                var user1 = main.Find<Sys_User>(dto.UserID);
                var user2 = ef.Find<Sys_User>(dto.UserID);

                if (user1 == null)
                {
                    return Fail("未找到该用户");
                }

                user1.Age = dto.Age;
                user1.Avatar = dto.Avatar;
                user1.Phone = dto.Phone;
                user1.NickName = dto.NickName;
                user1.RealName = dto.RealName;
                user1.TenantID = tanentID;
                user1.LoginName = dto.LoginName;

                user2.Age = dto.Age;
                user2.Avatar = dto.Avatar;
                user2.Phone = dto.Phone;
                user2.NickName = dto.NickName;
                user2.RealName = dto.RealName;
                user2.TenantID = tanentID;
                user2.LoginName = dto.LoginName;

                main.Attach(user1);
                ef.Attach(user2);

                var list1 = main.Set<User_AreaRoleDeptCategory>().Where(x => x.UserID == dto.UserID).ToList();
                var list2 = ef.Set<User_AreaRoleDeptCategory>().Where(x => x.UserID == dto.UserID).ToList();

                main.RemoveRange(list1);
                ef.RemoveRange(list2);

                var list = new List<User_AreaRoleDeptCategory>();
                foreach (var item in dto.DeptRoleCategory)
                {
                    int i = dto.DeptRoleCategory.IndexOf(item);
                    if (item.Length == 3)
                    {
                        list.Add(new User_AreaRoleDeptCategory() { DeptID = item[0], AreaID = dto.AreaID[i], UserID = dto.UserID, UAID = "UA" + snow_id.CreateId().ToString(), RoleID = item[1], CategoryID = item[2] });
                    }
                    else
                    {
                        list.Add(new User_AreaRoleDeptCategory() { DeptID = item[0], AreaID = dto.AreaID[i], UserID = dto.UserID, UAID = "UA" + snow_id.CreateId().ToString(), RoleID = item[1], CategoryID = "" });
                    }

                }
                main.AddRange(list);
                ef.AddRange(list);
            }

            var flag1 = main.SaveChanges() > 0;
            var flag2 = ef.SaveChanges() > 0;
            return Output(flag1 && flag2, "操作成功！", "操作失败！");
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public OutputResult UpdatePwd(InUpdatePwd dto)
        {
            string old_pwd = _Security.Rsa.Decrypt(dto.Old_pwd.Trim());
            string pwd1 = _Security.Rsa.Decrypt(dto.Pwd1.Trim());
            string pwd2 = _Security.Rsa.Decrypt(dto.Pwd2.Trim());
            string user_id = _contextAccessor.HttpContext?.User.Claims.First().Value;
            var user = ef.Find<Sys_User>(user_id);
            var main_user = main.Find<Sys_User>(user_id);
            string salt_pwd = _Security.Salt.Encrypt(old_pwd, user.Salt);

            if (!user.Pwd.Equals(salt_pwd))
            {
                return Fail("旧密码不正确!");
            }
            if (!pwd1.Equals(pwd2))
            {
                return Fail("二次密码确认不一致!");
            }
            string new_pwd = _Security.Salt.Encrypt(pwd2, user.Salt);
            user.Pwd = new_pwd;
            main_user.Pwd = new_pwd;
            ef.Attach(user);
            main.Attach(main_user);
            main.SaveChanges();
            var flag = ef.SaveChanges() > 0;
            return Output(flag, "操作成功", "操作失败");
        }
    }
}
